package com.smartlink.app.util;

import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2016/4/22.
 */
public class JSONUtils {
    /**
     * 将JSONO串封装成bean
     *
     * @param jsonString
     * @param clazz
     * @return
     * @throws Exception
     * @throws IllegalAccessException
     */
    public static Object toBean(String jsonString, Class clazz) throws Exception {
        Object object = clazz.newInstance();
        JSONObject jsonObject = new JSONObject(jsonString);

        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            String newFieldName = fieldName.replaceFirst(fieldName.substring(0, 1), fieldName.substring(0, 1).toUpperCase());
            Method method = clazz.getMethod("set" + newFieldName, new Class[]{String.class});
            String contentString = jsonObject.getString(fieldName);
            method.invoke(object, contentString);
        }
        return object;
    }
}
